import { SERVER_PREFIX } from './env'
import store from '../store/index.js'
let modalIsShowing = false

const request = (opt, isSilent = false) => {
  const { contentType } = opt
	opt = opt || {};
	if (opt.label === undefined ) {
		if(!opt.url.startsWith('http')) {
			opt.url = (SERVER_PREFIX + opt.url) || '';
		}
	}
	opt.data = opt.data || null;
	opt.method = opt.method || 'POST';
	opt.header = Object.assign({
		"Content-Type": contentType || "application/json"
	}, opt.header)
  
  const { token } = store.state
  if(token) {
    opt.header['Authorization'] = 'Bearer ' + token
  }
  
	return new Promise((resolve, reject) => {
		uni.request({
			...opt,
			success: (response) => {
        console.log('request', JSON.stringify(opt, null, '  '));
				console.log('response', JSON.stringify(response, null, '  '));
				const { data } = response
        const { msg, code } = data
				if(code !== 200) {
					if (!isSilent) {
            uni.showModal({
            	content: msg,
              showCancel: false
            })
            reject()
					}
				}
        resolve(data)
			},
			fail: (res) => {
				console.log('fail', JSON.stringify(res));
				reject(res)
			}
		})
	})
}

export default request

